package wickethub.web.page;

import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.RequiredTextField;
import org.apache.wicket.markup.html.form.TextArea;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.validation.IValidatable;
import org.apache.wicket.validation.IValidator;
import org.apache.wicket.validation.validator.AbstractValidator;
import org.apache.wicket.validation.validator.StringValidator;
import org.apache.wicket.validation.validator.UrlValidator;

import wickethub.domain.Component;
import wickethub.web.components.LocalizedEnumDropDownChoice;

public class EditComponentPanel extends Panel {
	
	public EditComponentPanel(String id, IModel<Component> model) {
		super(id);
		setDefaultModel(model.getObject() instanceof Component ? model : new Model<Component>(new Component()));

    	final Form<Component> form = new Form<Component>("form", new CompoundPropertyModel<Component>(getDefaultModel()));
		
		form.add(new RequiredTextField<String>("title").add(StringValidator.maximumLength(40)));
		form.add(new TextArea<String>("description"));
		
		IValidator<String> val = new UrlValidator();
		form.add(new TextField<String>("websiteUrl").add(val));
		form.add(new TextField<String>("examplesUrl").add(val));
		TextField<String> jarUrl = new TextField<String>("jarUrl");
		jarUrl.add(val);
		jarUrl.add(new AbstractValidator<String>() {
			
			@Override
			protected void onValidate(IValidatable<String> validatable) {
				if (!(validatable.getValue().toLowerCase().endsWith(".pom") || validatable.getValue().toLowerCase().endsWith(".jar"))) {
					error(validatable);
				}
			}
			
			@Override
        	protected String resourceKey() {
        		return "pomOrJarError";
        	}
			
		});
		form.add(jarUrl);
		
		form.add(new LocalizedEnumDropDownChoice<Component.License>("license", Component.License.values()));
		
		add(form);
        
    }
    
}